/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.uah.es.snomedctsubsetextractor;

import com.mysql.jdbc.Connection;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Luis
 */
public class SubsetExtractor {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Connection conn;
        String sql;
        PreparedStatement stmt;
        ResultSet rs;

        
        System.out.println("::::::::START - Extractor::::::::");
        
        try {
            BufferedReader inSubset = null;

            PrintStream outSubset = null;

            String strLine;

            String subsetsOriginal = "";

            // Ruta donde se encuentra el fichero de configuraci�n de la base de datos.
            String pathdb = System.getProperty("user.dir") + File.separator + "etc" + File.separator + "confdb.xml";

            String path = System.getProperty("user.dir") + File.separator + "etc" + File.separator;

            //inSubset = new BufferedReader(new FileReader(System.getProperty("user.dir") + File.separator + "etc" + File.separator + "CancerOvario-Subset.txt"));
            inSubset = new BufferedReader(new FileReader(path + args[0]));

            //outSubset = new PrintStream(new FileOutputStream(System.getProperty("user.dir") + File.separator + "etc" + File.separator + "CancerOvario-Subset-Expand-IsA-H3.txt"));
            outSubset = new PrintStream(new FileOutputStream(path + args[0].substring(0, args[0].length() - 4) + "-Expand-" + args[1].substring(0, args[1].length() - 4) + "-H" + args[2] + ".txt"));

            PrintStream outDB = new PrintStream(new FileOutputStream(path + args[0].substring(0, args[0].length() - 4) + "-Expand-" + args[1].substring(0, args[1].length() - 4) + "-H" + args[2] + "-DB.txt"));

            // Lista de conceptos
            ArrayList<Integer> concepts = new ArrayList<Integer>();

            SNOMEDCTConfigurator DBConf = new SNOMEDCTConfigurator(pathdb);

            //Read File Line By Line
            while ((strLine = inSubset.readLine()) != null) {

                String[] arrayConcept = strLine.split(";");
                // Print the content on the console
                concepts.add(Integer.valueOf(arrayConcept[0]));

                subsetsOriginal += arrayConcept[0] + ",";

                outSubset.println(strLine);
            }

            subsetsOriginal = subsetsOriginal.substring(0, subsetsOriginal.length() - 1);

            //Close the input stream
            inSubset.close();


            if (DBConf.getValue("sgbd").compareToIgnoreCase("mysql") == 0) {


                Class.forName("com.mysql.jdbc.Driver").newInstance();
                conn = (Connection) DriverManager.getConnection("jdbc:mysql:" + DBConf.getValue("url") + DBConf.getValue("schema"), DBConf.getValue("user"), DBConf.getValue("password"));

                sql = "SELECT DISTINCT conceptidSon, conceptSon FROM subsets WHERE conceptidRoot in (" + subsetsOriginal + ")";

                //System.out.println("SQL: " + sql);

                stmt = conn.prepareStatement(sql);
                rs = stmt.executeQuery();

                while (rs.next()) {
                    if (concepts.contains(rs.getInt("conceptidSon")) == false) {
                        // Print the content on the console
                        concepts.add(rs.getInt("conceptidSon"));

                        outSubset.println(rs.getInt("conceptidSon") + ";" + rs.getString("conceptSon"));
                    }

                }

                sql = "SELECT * FROM subsets";
                //INTO OUTFILE '/tmp/" + args[0].substring(0, args[0].length() - 4) + "-DB.txt'";
                stmt = conn.prepareStatement(sql);
                rs = stmt.executeQuery();

                while (rs.next()) {
                    outDB.println(rs.getString(1) + "\t" + rs.getString(2) + "\t"
                            + rs.getString(3) + "\t" + rs.getString(4) + "\t"
                            + rs.getString(5) + "\t" + rs.getString(6) + "\t"
                            + rs.getString(7));

                }

                // BORRAMOS LA TABLA SUBSETS
                sql = "DELETE FROM subsets";
                stmt = conn.prepareStatement(sql);
                stmt.executeUpdate();


                rs.close();
                stmt.close();
                conn.close();
            } else {
                throw new UnsupportedOperationException("Not supported yet.");
            }


            System.out.println("::::::::THE END - Extractor::::::::");
        } catch (SQLException ex) {
            Logger.getLogger(SubsetExtractor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(SubsetExtractor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(SubsetExtractor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(SubsetExtractor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SubsetExtractor.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
}
